package com.sky.controller.admin;

import com.sky.dto.CategoryDTO;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 目标:
 *
 * @author YUE
 * @date 2024/6/11 17:01
 */
@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        dishService.save(dishDTO);
        cleanCache("dish_"+ dishDTO.getCategoryId());
        return Result.success();
    }

    /*
        菜品分页查询
     */
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pr = dishService.page(dishPageQueryDTO);
        return Result.success(pr);
    }

    /*
    删除菜品 单一删除 批量删除
 */
    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    /*
        1 : 根据id查询回显菜品
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询回显菜品")
    public Result<DishVO> getById(@PathVariable Long id) {
        DishVO dv = dishService.getByIdDishFlavor(id);
        return Result.success(dv);
    }

    /*
       2 : 修改数据
     */
    @PutMapping
    @ApiOperation("修改数据")
    public Result update(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);
        cleanCache("dish_*");

        return Result.success();
    }

    /*
      启用禁用
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用")
    public Result startOrStop(@PathVariable Integer status, Long id) {
        dishService.startOrStop(status, id);
        cleanCache("dish_*");

        return Result.success();
    }

    /*
      根据分类id查询菜品
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> categoryId(Long categoryId) {
       List<Dish> dish = dishService.getByCategoryId(categoryId);
       return Result.success(dish);

    }

    public void cleanCache(String patten){
        Set keys = redisTemplate.keys(patten);
        redisTemplate.delete(keys);
    }
}
